package com.ebocy.hammer.core.socket.server;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.ebocy.hammer.core.constants.GameConstants;
import com.ebocy.hammer.core.db.DBConnManager;
import com.ebocy.hammer.core.init.MessageLoader;
import com.ebocy.hammer.core.log.EbocyLogManager;
import com.ebocy.hammer.core.task.HeartBeatTask;
import com.ebocy.hammer.core.util.Config;

/**
 * main server
 *2012-3-9@author yangshaobo
 */
public abstract class AbstractServer {
	// 定期执行服务
	protected static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
	
	protected static Logger logger = EbocyLogManager.getSystemLogger();

	/**
	 * start server
	 */
	public void startServer(){
		this.startDBConn();
		this.initialization();
		this.checkServer();
		this.registerHandlers();
		this.startSocketService();

	}

	protected abstract void registerHandlers();

	/**
	 * check server status
	 */
	protected abstract void checkServer();

	/**
	 * run socket acceptor
	 */
	protected  void startSocketService(){
	}

	/**
	 * load message class and initialization
	 */
	protected void initialization(){
		Config.getInstance().init();
		MessageLoader.initMessage(MessageLoader.class);	// 加载所有游戏消息类
		scheduler.scheduleWithFixedDelay(new HeartBeatTask(), GameConstants.CLIENT_TIME_OUT_MINUTE, GameConstants.CLIENT_TIME_OUT_MINUTE, TimeUnit.MINUTES);	// 启动心跳检查
	}
	
	protected void init(Class clazz){
		MessageLoader.initMessage(clazz);
	}

	/**
	 * initialization db connection
	 */
	private void startDBConn(){
		DBConnManager.initConn();
	}

	/**
	 * stop server
	 */
	public  void stopServer(){
		DBConnManager.closeConn();
		System.exit(0);
	}
}
